package client

import (
	"4-11zk/common/proto/user"
	"context"
	"fmt"
	"google.golang.org/grpc"
)

type Handlers func(ctx context.Context, client user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handlers Handlers) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
	}
	defer conn.Close()
	// 2. 实例化gRPC客户端
	client := user.NewUserClient(conn)
	// 3.组装请求参数
	req, _ := handlers(ctx, client)
	return req, nil
}

func Login(ctx context.Context, req *user.LoginReq) (*user.LoginResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.Login(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.LoginResp), nil
}

func PlanAdd(ctx context.Context, req *user.PlanAddReq) (*user.PlanAddResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.PlanAdd(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.PlanAddResp), nil
}
func PlanDel(ctx context.Context, req *user.PlanDelReq) (*user.PlanDelResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.PlanDel(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.PlanDelResp), nil
}
func OrderAdd(ctx context.Context, req *user.OrderAddReq) (*user.OrderAddResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.OrderAdd(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.OrderAddResp), nil
}
func OrderCall(ctx context.Context, req *user.OrderCallReq) (*user.OrderCallResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.OrderCall(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.OrderCallResp), nil
}
